#include <errno.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <std::string.h> 
#include <sys/mman.h> 
#include <sys/types.h> 
#include <unistd.h>



int fd;
void testnobatch(char* buf, int n)
{
	for(int i = 0; i < 128; ++i)
	{
		for(int k = 0; k + 1024< n; k+=1024)
		{
			write(fd, buf+k, 1024);
		}
		fsync(fd);
	}

	
}

void testbatch(char* buf, int n)
{
	for(int i = 0; i < 128; ++i)
	{
		char b[1024*1024];
		for(int k = 0; k + 1024< n; k+=1024)
		{
			memcpy(b+k, buf+k, 1024);
			
		}

		write(fd, buf+k, 1024);
		fsync(fd);
	}

	
}

void testmmap(char* buf, int n)
{
	int size = 1024*1024;
	char * buffer = NULL;
	
	for(int i = 0; i < 128; ++i, size += 1024*1024)
	{
		ftruncate(fd, size); 
	
		buffer = (char *)mmap(NULL, 1024*1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		
		for(int k = 0; k + 1024< n; k+=1024)
		{
			memcpy(buffer+k, buf+k, 1024);
		}
		msync( buffer, 1024*1024, MS_SYNC);
		munmap(buffer, 1024*1024);
	}

	
}



int main(int argc, char**argv)
{
	char buf[1024*1024];
	int mode = atoi(argv[1]);
	fd = open(argv[2], O_APPEND | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR);
	if(fd < 0) exit(-1);
	
	if(mode == 0) testnobatch(buf, 1024*1024);
	else if(mode == 1) testbatch(buf, 1024*1024);
	else testmmap(buf, 1024*1024);

	close(fd);
	

}

